import React, { Component } from 'react'
import { RouteComponentProps, withRouter } from "react-router-dom";
import DataCategory from "../../../../../types/DataCategory";
import { FormInstance } from "antd/lib/form";
import { getRes } from "../../../../../configFile";
import { Button, Card, Form, Input, message, Popconfirm, Space, Spin } from "antd";
import { Store, ValidateErrorEntity } from "rc-field-form/lib/interface";
import { modifyDataCategory, queryCategory, queryCategoryOptions } from "../../../../../requests/DataCategory";
import DataType from "../../../../../types/DataType";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons/lib";

interface IProps extends RouteComponentProps<{ id: string }> { }
interface IState {
    dataCategoryID: number
    isLoading: boolean
    dataCategoryInfo: DataCategory | undefined
    selectOptions: string[]
}
class SpecificModifyDataCategory extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            dataCategoryID: Number.parseInt(this.props.match.params.id),
            dataCategoryInfo: undefined,
            selectOptions: []
        }
    }
    //创建Form引用
    formRef = React.createRef<FormInstance>()
    //创建添加选项引用
    addOptionRef: ((defaultValue?: any, insertIndex?: number | undefined) => void) | undefined;

    //模态框样式

    tailLayout = {
        wrapperCol: { offset: 4, span: 16 },
    };
    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };


    componentDidMount = async () => {
        try {
            const res = getRes(await queryCategory(this.state.dataCategoryID))
            if (res.isSuccessful === true) {
                this.setState({
                    ...this.state,
                    dataCategoryInfo: res.data
                })
                //设置表单域    实例不为空
                if (this.formRef.current)
                    this.formRef.current.setFieldsValue(res.data);
                //选择类型要请求已有选项
                if ((res.data as DataCategory).dataType === DataType.SELECT) {
                    const optionsRes = getRes(await queryCategoryOptions(this.state.dataCategoryID));
                    if (!optionsRes.isSuccessful) {
                        message.error("选项获取失败" + optionsRes.message);
                    } else {
                        optionsRes.data.forEach((item: string) => {
                            if (this.addOptionRef)
                                this.addOptionRef({ option: item })
                        })
                    }
                }
            } else {
                message.error("数据类型获取失败" + res.message)
            }
            this.setState({
                ...this.state,
                isLoading: false
            })
        } catch (err) {
            message.error(err.toString())
        }
    }

    //放弃修改
    modifyAbort = () => {
        this.props.history.goBack()
    }


    //提交失败
    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    //提交成功
    onFinish: (values: Store) => void = async values => {
        const paraTmp: { dataCategoryID: number, dataCategoryName: string } = {
            dataCategoryID: this.state.dataCategoryID,
            dataCategoryName: values.dataCategoryName,
        }
        console.log(values);
        
        this.setState({
            ...this.state,
            isLoading: true,
        })
        try {
            const res = getRes(await modifyDataCategory(paraTmp, values.selectList?.map((item: { option: string }) => item.option)))
            if (res.isSuccessful === true) {
                message.success("修改成功")
                this.props.history.goBack()
            } else {
                message.error("修改失败" + res.message)
            }
        } catch (err) {
            message.error(err.toString())
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }


    render() {
        return (
            <Spin spinning={this.state.isLoading}>
                <Card
                    extra={<Popconfirm
                        placement="topRight"
                        title='确定放弃更改吗？'
                        onConfirm={this.modifyAbort}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button danger>放弃更改</Button>
                    </Popconfirm>}
                    title={this.state.dataCategoryInfo?.dataCategoryName}
                >
                    <Form
                        onFinishFailed={this.onFinishFailed}
                        onFinish={this.onFinish}
                        ref={this.formRef}
                        {...this.layout}
                        name="modifyDataCategory"
                    >

                        <Form.Item
                            label="数据类型名"
                            name="dataCategoryName"
                            rules={[{ required: true }]}
                        >
                            <Input />
                        </Form.Item>


                        <Form.List name="selectList">
                            {(fields, { add, remove }) => {
                                //选择下才显示
                                if (!!this.state.dataCategoryInfo) {
                                    if (this.state.dataCategoryInfo.dataType === DataType.SELECT) {
                                        this.addOptionRef = add;
                                        return (
                                            <div>
                                                {fields.map((field, index) => (
                                                    <Form.Item
                                                        {...(index === 0 ? { ...this.layout } : { ...this.tailLayout })}
                                                        label={index === 0 ? '选项' : ''}
                                                        required={false}
                                                        key={field.key}
                                                    >
                                                        <Space style={{ alignItems: 'start' }}>
                                                            <Form.Item
                                                                name={[field.name, 'option']}
                                                                rules={[{ required: true, message: '选项不可省略' }]}
                                                            >
                                                                <Input placeholder="请输入选项或删除该选项" />
                                                            </Form.Item>

                                                            <MinusCircleOutlined
                                                                style={{ fontSize: '32px' }}
                                                                onClick={() => {
                                                                    remove(field.name);
                                                                }}
                                                            />
                                                        </Space>
                                                    </Form.Item>
                                                ))}
                                                <Form.Item
                                                    rules={[{ required: true, message: '选项不可为空' }]}
                                                    {...this.tailLayout}>
                                                    <Button
                                                        type="dashed"
                                                        onClick={() => {
                                                            add();
                                                        }}
                                                        style={{ width: '60%' }}
                                                    >
                                                        <PlusOutlined />新增选项
                                                    </Button>
                                                </Form.Item>
                                            </div>
                                        );
                                    }
                                }
                            }}
                        </Form.List>

                        <Form.Item {...this.tailLayout}>
                            <Button type="primary" htmlType="submit" size="large">
                                确认修改
                        </Button>
                        </Form.Item>
                    </Form>
                </Card>
            </Spin>
        )
    }
}

export default withRouter(SpecificModifyDataCategory)